package com.ang.hutool.excel.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.ang.hutool.excel.simpleDemos.WriterList;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

public class ExcelUtil {

    public static void downloadXlsx(HttpServletResponse response) throws IOException {
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter excelWriter = cn.hutool.poi.excel.ExcelUtil.getWriter();

        //构建数据
        WriterList listWriter = new WriterList();
        List<List<String>> rows = listWriter.getRows();
        excelWriter.write(rows, true);

        downloadMethod(response, excelWriter);
    }

    /**
     * 导出，指定文件名和Sheet名
     */
    public static void downloadXlsx1(HttpServletResponse response, String sheetName, String titleName, List list) throws Exception{
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter excelWriter = cn.hutool.poi.excel.ExcelUtil.getWriter();

        //使用renameSheet可以直接修改第一个Sheet名
        excelWriter.renameSheet(sheetName+"1");
        excelWriter.write(list,true);
        //继续新增Sheet，可以用setSheet
        excelWriter.setSheet(sheetName+"2");
        excelWriter.write(list,true);

        downloadMethod(response, excelWriter);
    }

    /**
     * 导出，指定标题名
     */
    public static void downloadXlsx2(HttpServletResponse response, String titleName,List list) throws Exception{
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter excelWriter = cn.hutool.poi.excel.ExcelUtil.getWriter();

        Map<String,String> aliasMap = new HashMap<>();
        aliasMap.put("name","姓名");
        aliasMap.put("age","年龄");
        //设置别名（标题名）
        excelWriter.setHeaderAlias(aliasMap);
        //只导出有别名的
        excelWriter.setOnlyAlias(true);

        excelWriter.write(list, true);

        downloadMethod(response, excelWriter);
    }

    /**
     * 导出指定的属性
     * 简化方法见：downloadXlsx4
     */
    public static <T> void downloadXlsx3(HttpServletResponse response, List<T> list, Map<String,String> aliasMap) throws Exception{
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter excelWriter = cn.hutool.poi.excel.ExcelUtil.getWriter();

        int rowIndex = 0;
        int colIndex = 0;

        //输入标题栏
        for (String key : aliasMap.keySet()) {
            excelWriter.writeCellValue(colIndex, rowIndex, aliasMap.get(key));
            //列+1
            colIndex ++;
        }
        //行+1，并且列置为0
        rowIndex ++;
        colIndex = 0;

        //遍历所有对象
        for (T t : list) {
            //获取对象所有属性
            Field[] fields = t.getClass().getDeclaredFields();
            for (Field field : fields) {
                System.out.println(field.toString());
                System.out.println(field.getName());
            }
            //过滤不需要的属性
            List<Field> fieldList = Arrays.stream(fields).filter(field -> aliasMap.keySet().contains(field.getName())).collect(Collectors.toList());

            //私有属性需要设置一下，否则获取不到value
            fieldList.forEach(field->{
                field.setAccessible(true);
            });

            for (Field field : fieldList) {
                excelWriter.writeCellValue(colIndex, rowIndex, field.get(t));
                //列+1
                colIndex ++;
            }
            //行+1，并且列置为0
            rowIndex ++;
            colIndex = 0;
        }

        downloadMethod(response, excelWriter);
    }

    /**
     * 导出指定的属性
     * downloadXlsx3的简化
     */
    public static <T> void downloadXlsx4(HttpServletResponse response, List<T> list, Map<String,String> aliasMap) throws Exception{
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter excelWriter = cn.hutool.poi.excel.ExcelUtil.getWriter();

        int rowIndex = 0;
        int colIndex = 0;

        //输入标题栏
        for (String key : aliasMap.keySet()) {
            excelWriter.writeCellValue(colIndex, rowIndex, aliasMap.get(key));
            //列+1
            colIndex ++;
        }
        //行+1，并且列置为0
        rowIndex ++;
        colIndex = 0;

        //遍历所有对象
        for (T t : list) {
            //bean转map
            Map<String,String> resultMap = BeanUtil.beanToMap(t, new TreeMap(), false, false);

            for (String key : resultMap.keySet()) {
                //只导出指定的属性
                if(aliasMap.keySet().contains(key)){
                    excelWriter.writeCellValue(colIndex, rowIndex, resultMap.get(key));
                    //列+1
                    colIndex ++;
                }
            }
            //行+1，并且列置为0
            rowIndex ++;
            colIndex = 0;
        }

        downloadMethod(response, excelWriter);

    }

    public static void downloadMethod(HttpServletResponse response, ExcelWriter excelWriter){
        ServletOutputStream out = null;

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=test.xlsx");
        response.setContentType("application/vnd.ms-excel;charset=gb2312");

        try{
            out = response.getOutputStream();
        }catch (IOException e){
            System.out.println("导出异常");
        }finally {
            excelWriter.flush(out, true);
            excelWriter.close();
//            IoUtil.close(out);
        }
    }

}
